package unitils;

import controller.Service;
import javafx.application.Platform;
import javafx.scene.image.ImageView;


public class Chopsticks {
//    筷子的编号 1-5
    private int id;
//    筷子的图片id
    private ImageView chopsticksImageView;
//    筷子的状态
    private boolean isUsed = false;

//    构造方法
    public Chopsticks(int id, ImageView chopsticksImageView){
        this.chopsticksImageView=chopsticksImageView;
        this.id=id;
    }

//    拿筷子的方法
    public synchronized boolean takeUp(Philosopher philosopher){
        if(!this.isUsed){
            this.isUsed=true;
            Platform.runLater(()->{
                this.chopsticksImageView.setVisible(false);
                String s;
                if(philosopher.getId()==this.id){
                    s="拿起左边筷子：";
                }else {
                    s="拿起右边筷子：";
                }
                philosopher.getTextArea().appendText(philosopher.getName()+s+this.id+"\n");
                    });
            return true;
        }else {
            return false;
        }
    }

//    放下筷子的方法
    public synchronized void putDown(Philosopher philosopher){
        this.isUsed=false;
        Platform.runLater(()->{
            this.chopsticksImageView.setVisible(true);
            String s;
            if(philosopher.getId()==this.id){
                s="放下左边筷子：";
            }else {
                s="放下右边筷子：";
            }
            philosopher.getTextArea().appendText(philosopher.getName()+s+this.id+"\n");
        });
        this.notifyAll();
    }

//    设置筷子的状态
    public boolean isUsed() {
        return isUsed;
    }

    public void setUsed(boolean used) {
        isUsed = used;
    }

    public int getId() {
        return id;
    }
}
